import {my_person_list, person_list} from "@/utils/common_data.js";

let socket = null;

export const websocket2_connect = (proxy, room)=> {
    console.log(`ws://129.0.0.65:8000/room/${room}/`)
    socket = new WebSocket(`ws://129.0.0.65:8000/room/${room}/`);
    // 连接完成以后 客户端自动触发
    socket.onopen = function (event) {
        let tag = document.createElement("div")
        tag.innerHTML = "连接已建立"
        document.getElementById("message2").appendChild(tag)
    }

    // 回调函数 当服务端有消息发送到时，自动触发
    socket.onmessage = function (event) {
        console.log("event.data2", event.data);
        if (my_person_list.value.includes(event.data)){
            proxy.$bus.emit("change_flag2", event.data)
        }else {
            let tag = document.createElement("div");
            tag.innerText = event.data;
            let msg = document.getElementById("message2")
            msg.prepend(tag)
        }
    }

    // 当连接关闭时，触发
    socket.onclose = function (event) {
        let tag = document.createElement("div")
        tag.innerHTML = "连接已断开"
        document.getElementById("message2").appendChild(tag)
    }
}
export const websocket2_sendMsg = ()=> {
    let tag = document.getElementById("txt2")
    console.log("tag.value", tag.value)
    socket.send(tag.value)
}

export const websocket2_send_flag = (flag)=> {
    socket.send(flag)
}

export const websocket2_closeConn = ()=> {
    // 向服务端发送断开连接
    socket.close();
}